package com.kermel.common.action;

import android.os.Handler;

import com.kermel.andromeda.action.AlarmAction;
import com.kermel.andromeda.common.action.FutureAction;
import com.kermel.common.util.DateTimeUtils;

public class FutureActionScheduler extends Handler {
    
    public boolean scheduleAlarm(AlarmAction alarmAction) {
        boolean result = false;
        
        if (alarmAction != null) {
            long triggerTime = alarmAction.getAlarmTriggerTime();
            
            // TODO: Should an exception be thrown when triggerTime isn't valid?
            if (AlarmAction.isTriggerTimeValid(triggerTime)) 
                result = scheduleFutureAction(alarmAction, triggerTime);
        }
        
        return result;
    }
    
    protected boolean scheduleFutureAction(FutureAction action, long triggerTime) {
        boolean result = false;
        
        if (action != null) {
            result = scheduleTimerToTriggerAction(action, triggerTime);
            action.setScheduled(result);
        }
        
        return result;
    }
    
    protected boolean scheduleTimerToTriggerAction(FutureAction action, long triggerTime) {
        boolean result = false;
        
        long delay = calculateDelayUntilFutureActionWillBeTriggered(triggerTime);
        
        System.out.println(String.format("FutureActionScheduler.scheduleTimerToTriggerAction() - triggerTime: %s; delay: %s (%d)", 
                DateTimeUtils.timeInMillisecondsToDateStringFull(triggerTime), 
                DateTimeUtils.timeInMillisecondsToDateStringFull(delay),
                delay));
        
        if (delay > 0) {
            result = postDelayed(action, delay);
        }
        
        return result;
        
    }
    
    protected long calculateDelayUntilFutureActionWillBeTriggered(long triggerTime) {
        long now = System.currentTimeMillis();
        
        long delay = Math.abs(triggerTime - now);
        
        return delay;
    }
    
    public boolean cancelAlarm(AlarmAction alarmAction) {
        boolean result = cancelFutureAction(alarmAction);
        return result;
    }
    
    protected boolean cancelFutureAction(FutureAction action) {
        boolean result = false;
        
        if (action != null) {
            removeCallbacks(action);
            result = true;
        }
        
        return result;
    }
}
